<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2020/5/5
 * Time: 12:30
 */

namespace app\common\library\agent\comission\impl;


use app\common\library\agent\comission\CommissionListener;
use app\common\model\CommissionLog;
use app\common\model\User;
use app\common\model\UserBalanceLog;
use think\Hook;
use think\Log;

class CommonCommissionListener implements CommissionListener
{
    /**
     * @param $commission
     * @param $order
     * @param $orderCreator
     * @param $orderGoods
     * @param $total_num
     * @param $user User 分佣获得者
     * @param $ratio
     */
    public function afterCommission($commission, $order, $orderCreator, $orderGoods, $total_num, $user, $ratio)
    {
        Log::record("分佣记录");
        $money = $commission * $total_num;
        $commissionLog = CommissionLog::create([
            'create_time' => time(),
            'user_id' => $user->user_id,
            'creator_id' => $order->user_id,
            'relate_id' => $order->order_id,
            'order_no' => $order->order_no,
            'goods_id' => $orderGoods->goods_id,
            'total_num' => $total_num,
            'commission_type' => "order",
            'goods_name' => $orderGoods->goods_name,
            'ratio' => null,
            'commision' => $commission,
            'price' => $orderGoods->goods_price,
            'money' => $money,
            'remark' => "{$orderCreator->nickName}购买{$total_num}个{$orderGoods->goods_name},{$user->nickName}获得分佣{$money}元",
            'month' => intval(date('m')),
            'year' => date('Y'),
            'wxapp_id' => 10001
        ]);
        Log::record("更新余额");
        $user->save(['balance' => $user->balance + $money, 'update_time' => time()]);
        Log::record("余额记录");
        UserBalanceLog::create([
            'user_id' => $user->user_id,
            'money' => $money,
            'create_time' => time(),
            'balance' => $user->balance
        ]);

        $data = [
            'commissionLog'=>$commissionLog,
            'user'=>$user,
            'orderCreator'=>$orderCreator
        ];

        Hook::listen("after_commission", $data);
    }
}